package com.pjbao.Service;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import com.pjbao.Service.model.ReportConfig;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpRequestBase;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pjbao.Service.EWEServices.RetCode;
import com.pjbao.Service.model.PersonInfoRecord;
import org.springframework.web.client.RestTemplate;

@Service
public class HttpForReportService {
    @Autowired
    ReportConfig reportConfig;
	@Autowired
	ReportService reportService;

	Logger logger = LoggerFactory.getLogger("api service v1");

	/***
	 * @param info
	 * @param interfaceStr
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> invokeG_X(PersonInfoRecord info, String interfaceStr) throws Exception {
		Map<String, Object> responseMap = invokeG_X(interfaceStr, info);
		return responseMap;
	}

	/***
	 * @param info
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings({ "unchecked", "null" })
	public Map<String, Object> invokeG_X(String idType,PersonInfoRecord info) throws Exception {
        String pjbIP = reportConfig.getIp();
        logger.info("从配置文件是获取到的IP是:"+ pjbIP);

		Map<String, Object> result = new HashMap<String, Object>();
		if("g1301".equals(idType)){
			result = invokG13(idType, info);
		}else if("g1302".equals(idType)){
			RetCode code = EWEServices.b402Query(pjbIP,info.getIdList(),info.getUserid());
			ObjectMapper mapper = new ObjectMapper();
			 String companyType[] = info.getIdList().split(":"); 
			 Map<String, Object> addTier = mapper.readValue(code.getData(), Map.class);
			result.put(companyType[0], addTier);		
		}else if("g201".equals(idType)){
			logger.info("进入g201==="+info.getName()+"=="+info.getCid()+"照片=="+info.getPhoto());
			result = g201toString(info, idType);
		}else{
			RetCode ret = invokeDataSource(idType, info);
			ObjectMapper mapper = new ObjectMapper();
			result = mapper.readValue(ret.getData(), Map.class);
		}
		return result;
	}
	
	public  RetCode invokeDataSource(String idType,PersonInfoRecord info) throws UnsupportedEncodingException{
        Logger logger = LoggerFactory.getLogger("api service v1");
        String pjbIP = reportConfig.getIp();
		RetCode ret = new RetCode();
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpRequestBase httpMethod=null;

		switch (idType) {
		case "corpTradeReport":
			httpMethod = new HttpGet(pjbIP +"b6/"+info.getComName()+"?token="+info.getUserid());
			break;
		case "ccorpAccountCheck":
			httpMethod = new HttpGet(pjbIP +"b5/"+info.getComName()+"/"+info.getCard()+"/"+info.getBankCode()+"?token="+info.getUserid());
			break;
		case "g501":
			logger.info("调用g501"+ pjbIP +idType+"/"+info.getName()+"/"+info.getCardID()+"?token="+info.getUserid());
			httpMethod = new HttpGet(pjbIP +idType+"/"+info.getName()+"/"+info.getCardID()+"?token="+info.getUserid());
			break;
		case "g502":
			logger.info("调用g502"+ pjbIP +idType+"/"+info.getCardID()+"/"+info.getPhone()+"?token="+info.getUserid());
			httpMethod = new HttpGet(pjbIP +idType+"/"+info.getCardID()+"/"+info.getPhone()+"?token="+info.getUserid());
			break;
		case "g503":
			logger.info("调用g503"+ pjbIP +idType+"/"+info.getName()+"/"+info.getCid()+"/"+info.getCardID()+"?token="+info.getUserid());
			httpMethod = new HttpGet(pjbIP +idType+"/"+info.getName()+"/"+info.getCid()+"/"+info.getCardID()+"?token="+info.getUserid());
			break;
		case "g7":
			httpMethod = new HttpGet(pjbIP +idType+"/"+info.getCardID()+"?token="+info.getUserid());
			break;
		case "g6":
			httpMethod = new HttpGet(pjbIP +idType+"/"+info.getName()+"/"+info.getCardID()+"/"+info.getCid()+"/"+info.getPhone()+"?token="+info.getUserid());
			break;

		case "certificateInfo":
			httpMethod = new HttpGet(pjbIP +"g10/"+info.getName()+"/"+info.getCid()+"?token="+info.getUserid());
			break;
		case "telInfo":
			logger.info("g11传参数:=="+info.getPhone()+"/"+info.getCompany()+"/"+info.getAddress()+"/"+info.getUnique()+"?token="+info.getUserid());
			httpMethod = new HttpGet(pjbIP +"g11/"+info.getPhone()+"/"+info.getCompany()+"/"+info.getAddress()+"/"+info.getUnique()+"?token="+info.getUserid());
			break;
		case "g12":
			logger.info("进入G12接口参数:getcid="+info.getCid()+"?token="+info.getUserid());
			httpMethod = new HttpGet(pjbIP +"g12/"+info.getCid()+"?token="+info.getUserid());
			break;
		case "g14":
			logger.info("进入G14接口参数:查询参数"+ pjbIP +idType+"/"+info.getName()+"/"+info.getCid()+"/"+info.getGid()+"/"+info.getMonth()+"?token="+info.getUserid());
			httpMethod = new HttpGet(pjbIP +idType+"/"+info.getName()+"/"+info.getCid()+"/"+info.getGid()+"/"+info.getMonth()+"?token="+info.getUserid());
			break;
		default:
			httpMethod = new HttpGet(pjbIP +idType+"/"+info.getName()+"/"+info.getCid()+"?token="+info.getUserid());
			break;
		}
		
		CloseableHttpResponse response=null;
	    try {
	        
	        	response = httpclient.execute(httpMethod);
	            ret.setHttp(response.getStatusLine().getStatusCode());
	            HttpEntity entity = response.getEntity();
	            if(ret.getHttp()==200){
	            	String content = EntityUtils.toString(entity);
	           	    parseContent(ret, content);
	            }
	            EntityUtils.consume(entity);
	        } catch (ClientProtocolException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally {
	            try {
					response.close();
					httpclient.close();
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
	            
	        }
		return ret;
	}
	
	public static void parseContent(RetCode ret, String content) {
		// parse the msg
		{
			String pattern = "\"msg\":\"([^\"]*)\"";
			Pattern r = Pattern.compile(pattern);
			Matcher m = r.matcher(content);
			if(m.find()){
				String msgStr = m.group(0).substring(7,m.group(0).length()-1);
				ret.setServiceDes(msgStr);
			}	
		}
		// parse the code
		{
			String pattern = "\"code\":[\\d-]+";
			Pattern r = Pattern.compile(pattern);
			Matcher m = r.matcher(content);
			if(m.find()){
				String codeStr = m.group(0).substring(7);
				ret.setService(Integer.parseInt(codeStr));
			}
			ret.setData(content);	
		}
	}

	public Map<String, Object> invokG13(String idType,PersonInfoRecord info ){
        String pjbIP = reportConfig.getIp();
		logger.info("进入invokg13");
		Map<String, Object> exportData=new HashMap<String, Object>();
		Map<String, Object> g12_1Map=new HashMap<String, Object>();
		String param1 = "pname:"+info.getName()+"@idcardNo:"+info.getCid();
		logger.info("3"+info.getIdList());
		String[] comtype = info.getIdList().split(":");
		logger.info("参数是:"+comtype[0]);
		if("falses".equals(comtype[0])){
		logger.info("参数是:"+param1);
			reportService.processCompanyRiskProfile(param1,"cpws",g12_1Map,info.getUserid());
			reportService.processCompanyRiskProfile(param1,"zxgg",g12_1Map,info.getUserid());
			reportService.processCompanyRiskProfile(param1,"sxgg",g12_1Map,info.getUserid());
			reportService.processCompanyRiskProfile(param1,"ktgg",g12_1Map,info.getUserid());
			reportService.processCompanyRiskProfile(param1,"fygg",g12_1Map,info.getUserid());
			reportService.processCompanyRiskProfile(param1,"wdhmd",g12_1Map,info.getUserid());
			reportService.processCompanyRiskProfile(param1,"ajlc",g12_1Map,info.getUserid());
			exportData.put("g1301",g12_1Map);
		}else{
			reportService.processCompanyRiskProfile(param1,comtype[0],g12_1Map,info.getUserid());
			exportData.put("g1302",g12_1Map);
		}
		return g12_1Map;
		
	}
	
	public Map<String, Object> g201toString(PersonInfoRecord info,String type) throws ClientProtocolException, IOException{
        String pjbIP = reportConfig.getIp();
		String params = "";
		CloseableHttpClient httpclient = HttpClients.createDefault();  
		HttpPost httppost = new HttpPost(pjbIP +type);
		List<NameValuePair> formparams = new ArrayList<NameValuePair>(); 
		formparams.add(new BasicNameValuePair("name", info.getName()));  
		formparams.add(new BasicNameValuePair("cid", info.getCid()));  
		formparams.add(new BasicNameValuePair("photo", info.getPhoto()));
		formparams.add(new BasicNameValuePair("token", info.getUserid()));
		UrlEncodedFormEntity uefEntity; 
		try {
			uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			httppost.setEntity(uefEntity); 
			CloseableHttpResponse response = httpclient.execute(httppost);  
			HttpEntity entity = response.getEntity();
			if (entity != null) { 
				params = EntityUtils.toString(entity, "UTF-8");
			}
			
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			 httpclient.close();
		} catch (Exception e) {
			logger.info("g201关闭连接失败");
		}
		logger.info("g201结束进入json转换");
		 ObjectMapper mapper = new ObjectMapper();
		 Map<String, Object> result = mapper.readValue(params, Map.class);  
		
		return result;
	}

}
